<?php


namespace App\Workerman;

use App\Services\ChatRoomService;
use App\Services\ChatService;
use GatewayWorker\Lib\Gateway;
use Illuminate\Database\QueryException;
use SebastianBergmann\CodeCoverage\Report\PHP;

define('PING', 'ping');//ping 心跳  返回1
define('BIND', 'bind');//bind 绑定  返回2
define('UNBIND', 'unbind');
define('GROUP_LIST', 'group_list');// 好友列表
define('GROUP_MESSAGE_RECORD', 'group_message_record');// 好友聊天记录
define('GROUP_BIND', 'group_bind');//创建聊天室
define('GROUP_MEMBER_JOIN', 'group_member_join');//聊天室-用户进入聊天室
define('GROUP_MEMBER_LEAVE', 'group_member_leave');//聊天室-用户离开聊天室
define('GROUP_SET_ORDER_TYPE', 'group_set_order_type');//聊天室-设置排序方式 自由排序 规则排序 固定排序
define('GROUP_SET_ORDER', 'group_set_order');//聊天室-设置自由排序-排序
define('GROUP_SET_ADMIN', 'group_set_admin');//聊天室-设置管理员
define('GROUP_MEMBER_BAN', 'group_member_ban');//聊天室-踢出用户
define('GROUP_MEMBER_VOICE', 'group_member_voice');//聊天室-用户禁言
define('GROUP_UPDATE', 'group_update');//聊天室-更新频道属性
define('GROUP_SEND_MSG', 'group_send_msg');//聊天室-发送消息
define('GROUP_MESSAGES', 'group_messages');//聊天室-推送消息

class Events
{

    public static function onWorkerStart($businessWorker)
    {
    
    }

    public static function onConnect($client_id)
    {
        Gateway::sendToClient($client_id, json_encode(array(
            'data' => ['type' => 'init'],
            'code' => 200,
            'msg' => 'success',
            'client_id' => $client_id
        )));
    }

    public static function onWebSocketConnect($client_id, $data)
    {
    
    }
	
	/**
	 * @param $client_id
	 * @param $message
	 * @return bool
	 */
    public static function onMessage($client_id, $message)
    {
        if ($debug = true) {
            $journal = [];
            $journal['client_id'] = $client_id;
            $journal['message'] = json_decode($message, true);
            echo json_encode($journal, JSON_UNESCAPED_UNICODE) . "\n";
        }
        try {
            $datas = json_decode($message, true);

            if (!$datas) {
                self::showMsg([], 400, '数据格式错误');
            }
            if ($datas['type'] !== BIND && !isset($_SESSION['member_id'])) {
                self::showMsg($client_id, 401, '登录状态已超时，请重新登录');
            }
            $return = '';
            // 根据类型执行不同的业务
            switch ($datas['type']) {
                case BIND:
                	echo '绑定设备'.PHP_EOL;
                	$return = (new ChatService($datas['token']))->bind($client_id, $datas);
                    break;
                case GROUP_BIND:
                    echo '添加好友'.PHP_EOL;
                    ChatService::group_bind($client_id, $datas);
                    break;
                case GROUP_MEMBER_JOIN:
                    ChatRoomService::group_member_join($client_id, $datas);
                    break;
                case GROUP_MEMBER_LEAVE:
                    ChatRoomService::group_member_leave($client_id, $datas);
                    break;
	            case GROUP_LIST:
	            	echo '好友列表'.PHP_EOL;
	            	$return = (new ChatService($datas['token']))->group_list($client_id, $datas);
	            	break;
	            case GROUP_MESSAGE_RECORD:
	            	echo '好友聊天记录'.PHP_EOL;
	            	$return = (new ChatService($datas['token']))->group_message_record($client_id, $datas);
	            	break;
                case GROUP_SEND_MSG:
                	echo '发送聊天消息'.PHP_EOL;
                	$return = (new ChatService($datas['token']))->group_send_msg($client_id, $datas);
                    break;
                case UNBIND:
                    ChatRoomService::unbind($client_id, $datas);
                    break;
	            case PING:
	            	//心跳包不响应
					echo '定时心跳'.PHP_EOL;
	            	break;
                default :
                	echo '没有匹配的 type'.PHP_EOL;
                	Gateway::sendToCurrentClient('{"0":"error data format"}');
            }
            if ($return != false) {
            	self::showMsg($return, $return['code'], 'SUCCESS');
            }
        } catch (\Exception $e) {
            self::showMsg([], 500, $e->getMessage());
        }
    }

    public static function onClose($client_id)
    {
        echo "设备断开连接:" . $client_id . PHP_EOL;
    }
    

    public static function showMsg($data = [], $errno = '200', $errmsg = 'SUCCESS')
    {
        $return['code'] = $errno;
        $return['msg'] = $errmsg;
        $return['data'] = $data;
        if ($errno == 401) {
            return Gateway::closeClient($data, json_encode($return));
        } else {
        	return Gateway::sendToCurrentClient(json_encode($return));
        }
    }
}
